package com.lun.blog.controller.web;

import com.lun.blog.pojo.Comment;
import com.lun.blog.pojo.User;
import com.lun.blog.service.BlogService;
import com.lun.blog.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * @Function : CommentController
 * @Description:
 * @Param:
 * @version: v1.0.0
 * @author: fanglj5
 * @date : 2021/3/17
 * Modification History:
 * Date Author Version Description
 * -------------------------------------------------------------
 * 时间 作者 版本号 修改原因
 */
@Controller
@RequestMapping("/web/comment")
public class CommentController {

    @Autowired
    CommentService commentService;
    @Autowired
    BlogService blogService;

    @GetMapping("/comments/{blogId}")
    public String comments(@PathVariable Long blogId, Model model){

        model.addAttribute("comments",commentService.getByBlogId(blogId));
        return "blog :: commentList";
    }

    @PostMapping("/comments")
    public String saveComment(Comment comment, HttpSession session){
        comment.setBlog(blogService.getBlog(comment.getBlog().getId()));
        User user = (User) session.getAttribute("user");
        if(user != null){
            comment.setAdminComment(true);
            comment.setAvatar(user.getAvatar());
        }else {
            comment.setAvatar("/images/avatar.png");
            comment.setAdminComment(false);
        }
        commentService.saveComment(comment);
        return "redirect:/web/comment/comments/"+comment.getBlog().getId();
    }
}
